import request from '@/utils/request';
import { docUrl } from '@/constants/constant'
// import axios from 'axios'
export class Upload {
  constructor (obj) {
    this.eleId = obj.eleId; // inputid
    this.inputFileName = obj.inputFileName; // 上传文件名称
    // this.uploadUrl = obj.uploadUrl // 上传地址
    this.callback = obj.callback; // 回调函数
    this.businessId = obj.businessId; // 业务唯一号
    this.businessType = obj.businessType; // 资料类型0：检查1：检验 2：诊断3：会诊4：MDT5：教学视频）
    this.systemId = obj.systemId; // 业务系统唯一号
    // this.accessKey = obj.accessKey // 业务系统访问秘钥
    // this.domainId = obj.domainId // 存储域id
    this.orgCode = obj.orgCode; // 机构唯一号
    this.departCode = obj.departCode; // 检查科室代码
    this.modality = obj.modality; // 检查类型
    this.partLength = 1024 * 1024 * 5; // 分段上传长度，默认5M
    this.queueList = []; // 上传队列
    this.failList = []; // 失败队列
    this.dom = document.getElementById(this.eleId);
  }

  getUuid () {
    let _time = new Date().getTime();
    let guid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
      let r = (_time + Math.random() * 16) % 16 | 0;
      _time = Math.floor(_time / 16);
      return (c === 'x' ? r : (r & 0x3 | 0x8)).toString(16);
    });
    return guid;
  }

  // 设置上传队列--文件选择时触发 paras-资料配置项
  setUploadQueue (paras) {
    if (this.dom.files.length === 0) {
      return;
    }
    // this.queueList
    // 判断队列是否有相同文件
    for (let i = 0; i < this.dom.files.length; i++) {
      let _fileId = this.getUuid();
      var _file = this.dom.files[i];
      let typeCode = '';
      let upUrl = docUrl + '/upload';
      // 获取相同文件
      let sameFile = this.queueList.filter(item => {
        return item.requestParas.file_name === _file.name && item.requestParas.file_size === _file.size;
      });
      if (sameFile.length > 0) {
        this.callback.sameCallBack && this.callback.sameCallBack(_file);
        break;
      }
      if (paras.format_code === 'DICOMDIR' || paras.format_code === 'AECG' || paras.format_code === 'SECTION') {
        typeCode = 'Image';
      } else {
        typeCode = 'Request';
      }
      // 根据文件类型设置上传地址
      let lastIndex = _file.name.lastIndexOf('.');
      let type = _file.name.substr(lastIndex + 1).toLowerCase();
      if (type === 'aecg') {
        upUrl += '/image-aecg';
      } else if (type === 'pdf' || type === 'jpg' || type === 'png' || type === 'bmp') {
        upUrl += '/exam-document';
      } else if (type === 'rar' || type === '7z' || type === 'zip') {
        upUrl += '/image-dicom';
      } else if (type === 'mp4') {
        upUrl += '/image-mp4';
      }
      let year = _file.lastModifiedDate.getFullYear();
      let month = _file.lastModifiedDate.getMonth() + 1;
      let date = _file.lastModifiedDate.getDate();
      let hour = _file.lastModifiedDate.getHours();
      let minute = _file.lastModifiedDate.getMinutes();
      let second = _file.lastModifiedDate.getSeconds();
      console.log('资料修改时间', `${year}-${month}-${date} ${hour}:${minute}:${second}`);
      let _data = {
        uploadUrl: upUrl,
        file: this.dom.files[i],
        fileId: _fileId,
        start: 0,
        end: this.partLength,
        pecent: 0,
        reUpload: false, // 需要重新上传
        fileParent: paras,
        requestParas: {
          business_id: this.businessId,
          business_type: this.businessType,
          business_time: `${year}-${month}-${date} ${hour}:${minute}:${second}`,
          format_code: paras.format_code,
          file_name: _file.name,
          file_size: _file.size,
          type_code: typeCode,
          position: 0,
          systemId: this.systemId,
          modality: this.modality,
          org_code: this.orgCode,
          depart_code: this.departCode,
          folder_flag: paras.id
        } // 上传参数
      };
      this.queueList.push(_data);
      if (this.callback) {
        this.callback.insert && this.callback.insert(_data);
      }
    }
  }

  // 获取文件分割片段
  getSplitData (queue) {
    queue.end = queue.end <= 0 ? this.partLength : queue.end;
    queue.requestParas.position = queue.start;
    if (queue.start < queue.end) {
      let blob = queue.file.slice(queue.start, queue.end);
      let fd = new FormData();
      fd.append(this.inputFileName, blob);
      for (let key in queue.requestParas) {
        fd.append(key, queue.requestParas[key]);
      }
      return fd;
    }
    return null;
  }

  // 文件片段上传成功回调
  uploadSuccess (res) {
    let _queue = this.queueList[0];
    if (!_queue) return;
    if (res.position) {
      _queue.end = Number(res.position);
      _queue.pecent = 100 * (_queue.end / _queue.file.size);
    }
    if (this.callback) {
      this.callback.process && this.callback.process(_queue);
    }
    if (res.document_id === '0') {
      _queue.start = _queue.end;
      _queue.end = _queue.end + this.partLength;
      this.uploadStart();
    } else {
      if (this.callback) {
        this.callback.finish && this.callback.finish(_queue);
      }
      this.queueList.shift();
      this.uploadStart();
    }
  }

  // 文件片段上传失败回调
  uploadFailure (queue, res) {
    if (res) {
      let errorTitle = res.toString();
      let errorText = '';
      if (errorTitle.indexOf('Cannot determine compressed stream type. Supported Archive Formats: Zip, GZip, Tar, Rar, 7Zip, LZip') > -1) {
        errorText = '文件格式不对，支持：Zip, GZip, Tar, Rar, 7Zip, LZip';
      } else if (errorTitle.indexOf('MakeDicomDir失败') >= 0) {
        errorText = '压缩包内不能包含文件夹，且文件格式必须为DCM格式影像文件';
      } else {
        errorText = '上传失败';
      }
      queue.errorText = errorText;
    } else {
      queue.errorText = '';
    }
    this.failList.push(queue); // 添加到失败队列
    this.queueList.shift();
    if (this.callback) {
      this.callback.error && this.callback.error(queue);
    }
    this.uploadStart();
  }

  // 开始上传
  uploadStart () {
    if (this.queueList.length === 0) {
      if (this.callback) {
        this.callback.complete && this.callback.complete();
      }
      return;
    }
    let queue = this.queueList[0];
    let _this = this;
    let _url = queue.uploadUrl + '?';
    for (let key in queue.requestParas) {
      _url = _url + key + '=' + queue.requestParas[key] + '&';
    }
    _url = _url.substr(0, _url.length - 1);
    request({
      url: _url,
      method: 'post',
      headers: {
        timeout: 300000
      },
      data: this.getSplitData(queue)
    })
      .then(res => {
        if (res.document_id) {
          _this.uploadSuccess(res);
        } else {
          queue.start = 0;
          queue.end = _this.partLength;
          _this.uploadFailure(queue, res);
        }
      }).catch((res) => {
        _this.uploadFailure(queue, res);
      });
  }

  // 重新上传失败文件
  uploadRecover () {
    if (this.failList.length > 0) {
      for (let i = 0; i < this.failList.length; i++) {
        this.queueList.push(this.failList[i]);
      }
      if (this.queueList.length > 0) {
        this.uploadStart();
        this.failList = [];
      }
    }
  }

  // 获取上传失败列表
  getFailList () {
    return this.failList;
  }

  // 删除上传队列文件
  deleleQueue (queue) {
    let index = this.queueList.findIndex(item => {
      return item.fileId === queue.fileId;
    });
    this.queueList.splice(index, 1);
    // 删除失败列表
    let index1 = this.failList.findIndex(item => {
      return item.fileId === queue.fileId;
    });
    this.failList.splice(index1, 1);
  }

  // 获取上传队列
  getQueueList () {
    return this.queueList;
  }

  // 设置上传队列
  setQueueList (arr) {
    this.queueList = arr;
  }
}
